package se.webbzon.oschi01.aes;

import java.io.IOException;
import java.io.InputStream;

public class HexInputStream extends InputStream {
	
	// The underlying input stream
	private final InputStream is;

	/*============================================================
	Constructors
	============================================================*/
	
	public HexInputStream(InputStream is) {
		this.is = is;
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Converts the provided hexadecimal string into an array 
	 * of bytes. **/
	public static final byte[] fromHex(String hex) {
		byte[] data = new byte[hex.length()/2];
		for (int i = 0; i < hex.length()/2; i++) {
			int upper = fromUTF8Hex(hex.charAt(2*i));
			int lower = fromUTF8Hex(hex.charAt(2*i+1));
			data[i] = (byte) (upper * 16 + lower);
		}
		return data;
	}
	
	@Override public int read() throws IOException {
		int upper = fromUTF8Hex(is.read());
		int lower = fromUTF8Hex(is.read());
		return 16 * upper + lower;
	}
	
	@Override public void close() throws IOException {
		is.close();
	}
	
	@Override public int available() throws IOException {
		return super.available() / 2;
	}

	@Override public boolean markSupported() {
		return false;
	}

	@Override public void reset() throws IOException {
		throw new IOException("Not supported!");
	}

	@Override public long skip(long n) throws IOException {
		return is.skip(2*n) / 2;
	}
	
	/*============================================================
	Private Methods
	============================================================*/

	/** Returns the value of the hexadecimal character represented
	 * by the UTF-8 character with the given character code. **/
	private static final byte fromUTF8Hex(int i) {
		if (i > 96)
			return  (byte) (i - 87);
		else if (i > 64)
			return  (byte) (i - 55);
		else
			return (byte) (i - 48);
	}
	
}
